import React, { useState, useEffect } from 'react';
import { useSwipeable } from 'react-swipeable';
import { useDispatch } from 'react-redux';
import { useSearchParams, useNavigate } from 'react-router-dom';
import { Button } from '@arco-design/web-react';
import InfoCard from './infoCard';
import LastTime from './lasttime';
import { getTrainConfig, getTrainDetail } from '@/api/train';
import { setTrainDuration } from '@/store/slices/room';
import TrainingLink from '@/components/TrainingLink';
import styles from './index.module.less';

export default function Index() {
    const dispatch = useDispatch();
    const [currentUser, setCurrentUser] = useState<any>(null); // 当前选中的用户
    const [pageDetail, setPageDetail] = useState<any>({});
    const [avatars, setAvatars] = useState<any[]>([]); // 原始头像列表
    const [displayAvatars, setDisplayAvatars] = useState<any[]>([]); // 用于显示的头像列表
    const [userList, setUserList] = useState<any[]>([]); // 所有用户数据
    const [searchParams] = useSearchParams();
    const trainingid = searchParams.get('trainingid') as any;
    const navigate = useNavigate();
    const [selectedIndex, setSelectedIndex] = useState<number>(0); // 在显示列表中的索引

    const handlers = useSwipeable({
        swipeDuration: Infinity,
        delta: 10,
        onSwiped: (eventData) => console.log("User Swiped!", eventData),
        onSwipedUp: () => console.log("Swiped Up!"),
        onSwipedDown: () => console.log("Swiped Down!"),
    });

    // 重新排列头像数组，使选中的头像在中间位置
    const rearrangeAvatars = (avatarsList: any[], centerIndex: number) => {
        if (avatarsList.length <= 1) return [...avatarsList];
        
        const reordered = [...avatarsList];
        const centerItem = reordered.splice(centerIndex, 1)[0];
        const middleIndex = Math.floor(reordered.length / 2);
        reordered.splice(middleIndex, 0, centerItem);
        
        return reordered;
    };

    useEffect(() => {
        getTrainDetail({ training_id: trainingid }).then(res => {
            if (res.code === 2000) {
                const characters = res.data?.characters || [];
                const detail = res.data?.detail || {};
                
                // 设置所有用户数据
                setUserList(characters);
                
                // 设置页面详情
                setPageDetail(detail);
                dispatch(setTrainDuration({ data: detail?.duration }));
                sessionStorage.setItem('TrainDuration', detail?.duration || '');
                
                // 创建头像列表
                const avatarList = characters.map((m: any) => ({
                    id: m.id,
                    image: m.avatar
                }));
                
                // 设置原始头像列表
                setAvatars(avatarList);

                // 计算默认选中的索引 - 确保在数据中间位置
                let defaultIndex = 0;
                if (avatarList.length > 0) {
                    // 如果是偶数，放在除以2的上一个位置
                    if (avatarList.length % 2 === 0) {
                        defaultIndex = Math.floor(avatarList.length / 2) - 1;
                    } else {
                        defaultIndex = Math.floor(avatarList.length / 2);
                    }
                }
                
                setSelectedIndex(defaultIndex);
                setCurrentUser(characters[defaultIndex]);
                
                // 重新排列数据，使选中的在中间位置
                const arrangedAvatars = rearrangeAvatars(avatarList, defaultIndex);
                setDisplayAvatars(arrangedAvatars);
                
                // 存储用户头像
                sessionStorage.setItem('USERPHOTO', avatarList[defaultIndex]?.image || '');
                
                // 获取默认的AI配置
                getAI(avatarList[defaultIndex]?.id);
            }
        });
    }, []);

    const onChoose = (id: any, originalIndex: number) => {
        // 在原始数组中查找真实索引
        const realIndex = avatars.findIndex(avatar => avatar.id === id);
        if (realIndex === -1) return;
        
        // 重新排列数据，使选中的在中间位置
        const arrangedAvatars = rearrangeAvatars(avatars, realIndex);
        setDisplayAvatars(arrangedAvatars);
        
        // 设置选中的索引 - 在重新排列后的数组中找到位置
        const centerIndex = Math.floor(arrangedAvatars.length / 2);
        if (arrangedAvatars.length % 2 === 0) {
            setSelectedIndex(centerIndex - 1);
        } else {
            setSelectedIndex(centerIndex);
        }
        
        // 设置选中的用户
        const selectedUser = userList.find(u => u.id === id);
        if (selectedUser) setCurrentUser(selectedUser);
        
        // 更新存储的头像和AI配置
        sessionStorage.setItem('USERPHOTO', userList.find(u => u.id === id)?.avatar || '');
        getAI(id);
    }

    const getAI = (key: any) => {
        if (key) {
            getTrainConfig(trainingid, key).then(res => {
                if (res.code === 2000) {
                    localStorage.setItem('ai_character_id', key);
                }
            });
        }
    }

    const goToTraining = () => {
        navigate(`/aiPracticeStart`);
        localStorage.setItem('training_id', trainingid);
    }

    return (
        <div className={`bg-white overflow-x-hidden ${styles.mainBody}`}>
            <div className={`${styles.topHeight} overflow-y-auto`}>
                <div className={`px-4 ${styles.topContent}`}>
                    <div className='flex justify-center items-center mb-[5px]' style={{ height: 59 }}>
                        {displayAvatars.map((avatar, index) => {
                            const isSelected = index === selectedIndex;
                            return (
                                <div 
                                    key={index} 
                                    className={`flex justify-center items-center ${isSelected ? styles.photoBg : ''}`}
                                    style={{
                                        width: isSelected ? 44 : 38,
                                        height: isSelected ? 44 : 38,
                                        position: 'relative',
                                        transition: 'all 0.3s ease',
                                        margin: '0 10px'
                                    }}
                                >
                                    <img 
                                        className={`rounded-full ${isSelected ? styles.fadeinelement : ''}`}
                                        onClick={() => {
                                            // 在原始数组中查找真实索引
                                            const realIndex = avatars.findIndex(a => a.id === avatar.id);
                                            if (realIndex !== -1) {
                                                onChoose(avatar.id, realIndex);
                                            }
                                        }}
                                        src={avatar.image} 
                                        alt={`Avatar ${index}`}
                                        style={{
                                            width: '100%',
                                            height: '100%',
                                            position: 'relative',
                                            cursor: 'pointer'
                                        }}
                                    />
                                </div>
                            );
                        })}
                    </div>
                    
                    <div {...handlers} style={{ width: '100%' }}>
                        <div className={styles.swiperBg}>
                            <InfoCard data={currentUser} />
                        </div>
                    </div>
                </div>
                
                <div className='px-4'>
                    <div className='mt-6 mb-[30px]'>
                        {pageDetail?.is_latest === 1 && <LastTime />}
                        <div className='text-xl font-bold mb-2.5 text-[#222222]'>{pageDetail?.title}</div>
                        
                        <div className='flex justify-between mb-2.5 text-xs text-[#22222299]'>
                            <div>
                                {pageDetail?.training_avatars?.filter(Boolean).map((m: string, index: number) => (
                                    <span key={index} className={`relative ${index > 0 ? '-ml-1.5' : ''} z-20 border border-2 rounded-full border-[#ffffff]`}>
                                        <img className='w-[18px] inline-block' src={m} alt="Training avatar" />
                                    </span>
                                ))}
                                {pageDetail?.training_all_times}人训练过
                            </div>
                            
                            <div>
                                训练过
                                <span style={{ color: '#DB0007' }}>{pageDetail?.current_training_times}</span>
                                次&nbsp;|&nbsp;
                                <TrainingLink trainingid={trainingid} title={pageDetail?.title} />
                            </div>
                        </div>
                        
                        <div className="flex">
                            <div className="text-[#666666] text-[11px] h-5 leading-5 px-2 border border-solid rounded-[30px] border-[rgba(0, 0, 0, 0.15)]">
                                {pageDetail?.first_category_name}
                            </div>
                        </div>
                    </div>
                    
                    <div className="mb-[30px]">
                        <div className={`text-base font-semibold mb-2.5 inline pb-0.5 text-[#222222] ${styles.bgYellow}`}>
                            陪练任务描述
                        </div>
                        
                        <div className="mt-2.5 text-[#222222]">
                            {pageDetail?.scene_description}
                        </div>
                        
                        <div className='flex rounded my-4 py-4 px-6' style={{ backgroundColor: 'rgba(242, 242, 242, 0.5)' }}>
                            <div style={{ width: '50%' }} className='text-center border-r border-solid border-inherit'>
                                <div className="text-[#999999] font-light text-xs leading-[18px]">AI的身份</div>
                                <div className="font-semibold text-[#222222]">顾客</div>
                            </div>
                            
                            <div style={{ width: '50%' }} className='text-center'>
                                <div className="text-[#999999] font-light text-xs leading-[18px]">你的身份</div>
                                <div className="font-semibold text-[#222222]">{pageDetail?.user_role}</div>
                            </div>
                        </div>
                    </div>
                    
                    <div>
                        <div className={`text-base inline pb-0.5 mb-2.5 font-semibold text-[#222222] ${styles.bgYellow}`}>
                            任务规则
                        </div>
                        
                        <div className="mb-10 mt-2.5 font-light text-[#222222]">
                            时间：在{pageDetail?.duration}分钟内完成
                            <br />
                            需求：满分{pageDetail?.max_score}分，{pageDetail?.pass_score}分以上算通过
                        </div>
                    </div>
                </div>
            </div>
            
            <div className={`${styles.footer} bg-white w-screen h-[82px] border-t border-[rgba(0, 0, 0, 0.12)] pt-1.5 px-5`}>
                <Button 
                    long 
                    className="text-lg h-[42px] font-extrabold rounded-3xl" 
                    onClick={goToTraining} 
                    style={{ backgroundColor: '#FFBC0D', color: '#222222' }}
                >
                    进入练习
                </Button>
            </div>
        </div>
    );
}